import paramiko as paramiko

from lib import logger

_black_dir_list = ['/', '/bin', '/boot', '/data', '/dev', '/etc', '/home', '/lib', '/lib64', '/media', '/mnt', '/opt',
                   '/proc', '/root', '/run', '/sbin', '/srv', '/sys', '/usr', '/var']


class SSHClient:
    """
    SSHClient
    """
    client: paramiko.SSHClient = None

    def __init__(self, host: str, port: int = 22, user: str = 'root', password: str = ''):
        """
        :param host: 远程主机地址
        :param port: 远程主机SSH端口
        :param user: 登录名
        :param password: 密码
        """
        self.host = host
        self.port = port
        try:
            self.client = paramiko.SSHClient()
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.client.connect(host, port, user, password, timeout=10)
        except BaseException as e:
            print(str(e))
            exit(0)

    def exec_command(self, command: str, print_output=True):
        """
        执行远程命令
        :param command: 命令
        :param print_output: 是否打印输出
        """
        stdin, stdout, stderr = self.client.exec_command(command=command)
        if print_output:
            out_res = stdout.read()
            err_res = stderr.read()
            if out_res or err_res:
                print(str(err_res, encoding='utf-8') if err_res else str(out_res, encoding='utf-8'))

    def make_symbol_link(self, source: str, target: str):
        """
        创建软链接
        :param source: 源文件/目录
        :param target: 目标文件/目录
        :return: void
        """
        link_path = '' if target is None else target.strip()
        if link_path == '':
            return
        if link_path in _black_dir_list:
            logger.print_error('你想干什么？')
            return

        unlink_command = 'rm -f %s' % link_path
        logger.print_info('[%s:%s] > %s' % (self.host, self.port, unlink_command))
        self.exec_command(unlink_command)

        command = 'ln -s %s %s' % (source, link_path)
        logger.print_info('[%s:%s] > %s' % (self.host, self.port, command))
        self.exec_command(command)

    def close(self):
        self.client.close()
